package com.potenza.training.dictionary.controller;

import com.potenza.training.dictionary.entity.HopeAddress;
import com.potenza.training.dictionary.server.HopeAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/hope")
public class HopeAddressController {

    @Autowired
    private HopeAddressService hopeAddressService;

    static List<HopeAddress> hopeAddressList = new ArrayList<HopeAddress>();

    /**
     * 获取所有的期望城市
     * @return
     */
    @GetMapping("/address")
    public List<HopeAddress> findAll(){
        return hopeAddressService.findAll();
    }

    /**
     * 获取经过处理的联动数据
     * @return
     */
    @GetMapping("/addresss")
    public List<HopeAddress> edit(){
        hopeAddressList.clear();
        List<HopeAddress> all = findAll();
        for (HopeAddress address : all) {
            hopeAddressList.add(new HopeAddress(address.getId(),address.getAddress(),address.getPid(),null));
        }

        List<HopeAddress> collect = hopeAddressList.stream().filter(hopeAddress ->
                hopeAddress.getPid() == 0
        ).map((menu) -> {
            menu.setChildren(getChildrens(menu, hopeAddressList));
            return menu;
        }).collect(Collectors.toList());

        return collect;
    }

    //递归查找所有菜单的子类菜单
    private static List<HopeAddress> getChildrens(HopeAddress root,List<HopeAddress> all){
        List<HopeAddress> children = all.stream().filter(linkageEntities -> Long.parseLong(String.valueOf(linkageEntities.getPid()))==root.getId()).map(linkageEntities -> {
            //1、递归找到子菜单
            linkageEntities.setChildren(getChildrens(linkageEntities,all));
            return linkageEntities;
        }).collect(Collectors.toList());
        return children;
    }

    @GetMapping("/addresss/grouping")
    public HopeAddress findByIdtow(@RequestParam String id){
        return hopeAddressService.findById(id);
    }
}
